from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.security import decode_token
from app.db.session import get_async_session
from app.models.user import User

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")


async def get_db() -> AsyncSession:
  async for session in get_async_session():
    yield session


async def get_current_user(
  token: str = Depends(oauth2_scheme),
  session: AsyncSession = Depends(get_db),
) -> User:
  try:
    payload = decode_token(token)
  except ValueError as exc:
    raise HTTPException(
      status_code=status.HTTP_401_UNAUTHORIZED, detail="凭证无效，请重新登录"
    ) from exc

  user_id = int(payload.get("sub", 0))
  user = await session.get(User, user_id)
  if not user:
    raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
  return user
